package com.servlet;

import com.model.User;
import com.service.UserService;
import com.service.UserServiceImpl;
import com.util.Constant;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        try {
            User user = userService.login(username, password);
            if (user != null) {
                // 登录成功，将用户信息存入session
                HttpSession session = request.getSession();
                session.setAttribute(Constant.USER_SESSION, user);
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                // 登录失败
                request.setAttribute("errorMsg", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "登录失败，请稍后再试");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 如果是get请求，直接跳转到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
}